package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.item.service.LockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.management.OperatingSystemMXBean;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author tangsy
 * @Description TODO
 * @date 2022/12/8 18:43
 * @Version 1.0
 */
@Service
public class LockServiceImpl implements LockService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public String lock() throws InterruptedException {
        String uuid = UUID.randomUUID().toString();
        while (!redisTemplate.opsForValue().setIfAbsent("lock",uuid,30,TimeUnit.SECONDS)){
            TimeUnit.MILLISECONDS.sleep(10);
        }
        return uuid;
    }

    @Override
    public void unlock(String uuid) {
//        String lock = redisTemplate.opsForValue().get("lock");
//        if (uuid.equals(lock)) {
//            redisTemplate.delete("lock");
//        }

        //删锁： 获取值 + 删除锁 = 原子操作
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        //删锁成功：
        //1、返回0： 删锁失败，有可能是别人的锁
        //2、返回1： 删锁成功

        Long lock = redisTemplate.execute(
                new DefaultRedisScript<>(script, Long.class),
                Arrays.asList("lock"),
                uuid
        );
        System.out.println("删锁结果："+lock);
    }
}
